import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { MemberLevel } from '../database/models';
import { utils } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 创建会员等级
 */
export async function createMemberLevel(ctx: Context): Promise<void> {
  const { name, level, description } = ctx.request.body as {
    name?: string;
    level?: number;
    description?: string;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser?.id;

  if (!userId) {
    error(ctx, ResponseCode.UNAUTHORIZED, '未认证的用户');
    return;
  }

  if (!name || level === undefined) {
    error(ctx, ResponseCode.BAD_REQUEST, '等级名称和等级数字不能为空');
    return;
  }

  // 检查当前用户下等级数字是否已存在
  const existing = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE user_id = ? AND level = ?', [userId, level]);
  if (existing) {
    error(ctx, ResponseCode.CONFLICT, '等级数字已存在');
    return;
  }

  const id = utils.generateUUID();
  await query(
    'INSERT INTO member_levels (id, user_id, name, level, description) VALUES (?, ?, ?, ?, ?)',
    [id, userId, name, level, description || null]
  );

  const newLevel = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE id = ? AND user_id = ?', [id, userId]);
  success(ctx, newLevel);
}

/**
 * 更新会员等级
 */
export async function updateMemberLevel(ctx: Context): Promise<void> {
  const { id, name, level, description } = ctx.request.body as {
    id?: string;
    name?: string;
    level?: number;
    description?: string;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser?.id;

  if (!userId) {
    error(ctx, ResponseCode.UNAUTHORIZED, '未认证的用户');
    return;
  }

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '等级ID不能为空');
    return;
  }

  const memberLevel = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE id = ? AND user_id = ?', [id, userId]);
  if (!memberLevel) {
    error(ctx, ResponseCode.LEVEL_NOT_FOUND);
    return;
  }

  const updates: string[] = [];
  const params: any[] = [];

  if (name !== undefined) {
    updates.push('name = ?');
    params.push(name);
  }
  if (level !== undefined) {
    // 检查新等级数字是否已被其他等级使用
    const existing = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE user_id = ? AND level = ? AND id != ?', [userId, level, id]);
    if (existing) {
      error(ctx, ResponseCode.CONFLICT, '等级数字已存在');
      return;
    }
    updates.push('level = ?');
    params.push(level);
  }
  if (description !== undefined) {
    updates.push('description = ?');
    params.push(description);
  }

  if (updates.length > 0) {
    params.push(id, userId);
    await query(`UPDATE member_levels SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`, params);
  }

  const updatedLevel = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE id = ? AND user_id = ?', [id, userId]);
  success(ctx, updatedLevel);
}

/**
 * 删除会员等级
 */
export async function deleteMemberLevel(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  const currentUser = ctx.state.user as any;
  const userId = currentUser?.id;

  if (!userId) {
    error(ctx, ResponseCode.UNAUTHORIZED, '未认证的用户');
    return;
  }

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '等级ID不能为空');
    return;
  }

  const memberLevel = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE id = ? AND user_id = ?', [id, userId]);
  if (!memberLevel) {
    error(ctx, ResponseCode.LEVEL_NOT_FOUND);
    return;
  }

  // 删除等级关系
  await query('DELETE FROM member_level_relations WHERE level_id = ?', [id]);
  
  // 删除等级
  await query('DELETE FROM member_levels WHERE id = ? AND user_id = ?', [id, userId]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询会员等级列表
 */
export async function getMemberLevelList(ctx: Context): Promise<void> {
  const { name } = ctx.request.body as { name?: string };

  const currentUser = ctx.state.user as any;
  const userId = currentUser?.id;

  if (!userId) {
    error(ctx, ResponseCode.UNAUTHORIZED, '未认证的用户');
    return;
  }

  let sql = 'SELECT * FROM member_levels WHERE user_id = ?';
  const params: any[] = [userId];

  if (name) {
    sql += ' AND name LIKE ?';
    params.push(`%${name}%`);
  }

  sql += ' ORDER BY level ASC';

  const levels = await query<MemberLevel>(sql, params);

  success(ctx, levels);
}

/**
 * 查询会员等级详情
 */
export async function getMemberLevelDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  const currentUser = ctx.state.user as any;
  const userId = currentUser?.id;

  if (!userId) {
    error(ctx, ResponseCode.UNAUTHORIZED, '未认证的用户');
    return;
  }

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '等级ID不能为空');
    return;
  }

  const memberLevel = await queryOne<MemberLevel>('SELECT * FROM member_levels WHERE id = ? AND user_id = ?', [id, userId]);
  if (!memberLevel) {
    error(ctx, ResponseCode.LEVEL_NOT_FOUND);
    return;
  }

  success(ctx, memberLevel);
}

